package org.test.springbootdisplaypage;


import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;

@SpringBootApplication
public class SpringbootDisplayPageApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootDisplayPageApplication.class, args);
    }



//下方的代码能够直接的运行appium服务器
    @Bean
    public CommandLineExecutor commandLineExecutor() {
        return new CommandLineExecutor();
    }
    @Configuration
    public class AppiumShutdownHook {

        CommandLineExecutor commandLineExecutor;

        public AppiumShutdownHook(CommandLineExecutor commandLineExecutor) {
            this.commandLineExecutor = commandLineExecutor;
        }

        @Bean
        public void registerShutdownHook(){
            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                commandLineExecutor.stopAppium();
            }));
        }
    }

    @Component
    public class CommandLineExecutor implements CommandLineRunner {

        private Process process;

        @Override
        public void run(String... args) throws Exception {
            try {
                // 执行命令
                process = Runtime.getRuntime().exec("appium --use-plugin=images");

                // 读取命令输出
                BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                }

                // 检查命令执行结果
                int exitValue = process.waitFor();
                if (exitValue == 0) {
                    System.out.println("命令执行成功");
                } else {
                    System.out.println("命令执行失败");
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public void stopAppium() {
            if (process != null) {
                process.destroy();
                System.out.println("Appium服务已停止");
            }
        }
    }
}